package com.steven;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class PicView {
    static JButton start_button;
    static JTextField fromField;
    static JTextField search_textField;
    static JTextField toField;
    static JTextField albumIndexField;
    static JTextField albumTotalField;
    static JFrame jFrame;
    static JLabel pname_label;
    static JLabel album;
    static JLabel index;
    static JTextField outDir_Field;
    static LinkedHashMap<String, Integer> res = new LinkedHashMap<>();

    public static void main(String[] args) {
        try {
            // 去除由于输入法导致的卡空白的问题 noddraw
            System.setProperty("sun.java2d.noddraw", "true");
            // 去除顶部设置按钮
            UIManager.put("RootPane.setupButtonVisible", false);
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
            new SingleGetPic().getAllPersons();
        } catch (Exception e) {
            //TODO exception
        }
        // 1, 创建一个顶层容器
        jFrame = new JFrame("全图网");
        ImageIcon icon_bj = new ImageIcon(Objects.requireNonNull(PicView.class.getResource("/bg.jpg")));
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // 2, 设置窗口大小
        jFrame.setSize(Math.min((icon_bj.getIconWidth() / 2), screenSize.width),
                Math.min((icon_bj.getIconHeight() / 2 + 60), screenSize.height));
        // 3, 设置窗口打开的位置
        jFrame.setLocationRelativeTo(null);
        // 4, 设置窗口不能改变大小
//        jFrame.setResizable(false);
        // 7, 设置窗口的图标
        ImageIcon icon = new ImageIcon(Objects.requireNonNull(PicView.class.getResource("/logo.png")));
        jFrame.setIconImage(icon.getImage());

        loadPD();

        // 5, 设置窗口可见
        jFrame.setVisible(true);

        // 6, 加载托盘
        loadTrayIcon(jFrame, icon);
    }

    public static void stopPD() {
        start_button.setText("开  始");
        SingleGetPic.isDownLoad = false;
        SingleGetPic.isErr = true;
        start_button.setForeground(new Color(92, 245, 10));
        fromField.setEnabled(true);
        toField.setEnabled(true);
        outDir_Field.setEnabled(true);
        albumIndexField.setEnabled(true);
    }

    public static void loadTrayIcon(JFrame jFrame, ImageIcon icon) {

        TrayIcon trayIcon;
        if (SystemTray.isSupported()) // 判断系统是否支持系统托盘
        {
            SystemTray tray = SystemTray.getSystemTray(); // 创建系统托盘
            icon.setImage(icon.getImage().getScaledInstance(15, 15, Image.SCALE_DEFAULT));
            ActionListener listener = e -> jFrame.setVisible(true);
            // 创建弹出菜单
            PopupMenu popup = new PopupMenu();
            //主界面选项
            MenuItem mainFrameItem = new MenuItem("OPEN");
            mainFrameItem.addActionListener(listener);

            //退出程序选项
            jFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "确定退出系统") == 0) {
                        System.exit(0);
                    }
//                    jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                }
            });

            final MenuItem exitItem = new MenuItem("EXIT");
            exitItem.addActionListener(e -> {
                exitItem.setEnabled(false);
                if (JOptionPane.showConfirmDialog(null, "确定退出系统") == 0) {
                    System.exit(0);
                }
                exitItem.setEnabled(true);
            });

            popup.add(mainFrameItem);
            popup.add(exitItem);

            trayIcon = new TrayIcon(icon.getImage(), jFrame.getTitle(), popup);// 创建trayIcon
            trayIcon.addActionListener(listener);
            try {
                tray.add(trayIcon);
            } catch (AWTException e1) {
                e1.printStackTrace();
            }
        }
    }

    // PD
    public static void loadPD() {
        JPanel jPanel = new JPanel();
        BackGroundImagePanle ingPanel = new BackGroundImagePanle();
        jPanel.setLayout(new GridLayout(7, 1, 30, 15));
        jPanel.setOpaque(false);
        ingPanel.add(jPanel);
        jFrame.add(ingPanel);

        // 创建一个搜索框
        JPanel line_0 = new JPanel(); // new FlowLayout(FlowLayout.LEFT)
        JLabel nums_label = new JLabel("0000:", JLabel.LEFT);
        nums_label.setOpaque(false);
        nums_label.setFont(new Font("楷体", Font.BOLD, 20));
        nums_label.setForeground(new Color(243, 4, 234));
        ArrayList<String> all = SingleGetPic.all;
        nums_label.setText("ALL:共 " + all.size() + " 名MM  ");

        JLabel search_label = new JLabel("检索:", JLabel.LEFT);
        search_label.setFont(new Font("楷体", Font.BOLD, 20));
        search_label.setOpaque(false);
        search_textField = new JTextField();
        search_textField.setForeground(Color.RED);
        search_textField.setOpaque(false);
        search_textField.setColumns(10);
        search_textField.setFont(new Font("楷体", Font.BOLD, 20));

        JComboBox<String> all_combobox = new JComboBox<>();
        all_combobox.addItem("-------请选择------");
        all_combobox.setFont(new Font("楷体", Font.BOLD, 20));
        all_combobox.setOpaque(false);
        all_combobox.setBackground(null);

        line_0.add(nums_label);
        line_0.add(search_label);
        line_0.add(search_textField);
        line_0.add(all_combobox);

        // 为搜索输入框 和 结果选择框创建点击事件
        search_textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                String search_textFieldText = search_textField.getText();

                if (!isEmpty(search_textFieldText)) {
                    int keyCode = e.getKeyCode();
                    if (keyCode == KeyEvent.VK_ENTER) {
                        // 清理结果集中数据
                        res.clear();
                        for (int i = 0; i < all.size(); i++) {
                            String peer = all.get(i).toUpperCase();
                            if (peer.contains(search_textFieldText.toUpperCase())) {
                                res.put(peer, i);
                            }
                        }
                        JOptionPane.showMessageDialog(jFrame, "共检索到" + res.size() + "条记录!");
                        all_combobox.removeAllItems();
                        if (res.size() == 0) {
                            all_combobox.addItem("未找到相关记录!");
                            return;
                        }

                        for (Map.Entry<String, Integer> entry : res.entrySet()) {
                            all_combobox.addItem(entry.getKey());
                        }
//                        checkPeerPersonAlbum(fromField.getText());
                    }
                }
            }
        });

        all_combobox.addActionListener(e -> {
            Object selectedItem = all_combobox.getSelectedItem();
            Integer ser_index = res.get(selectedItem);
            fromField.setText(ser_index + "");
            toField.setText(ser_index + "");
            if (!"null".equals(fromField.getText()))
                checkPeerPersonAlbum(fromField.getText());
//            if(!"null".equals(outDir_Field.getText())){
            if (outDir_Field.getText() != null) {
                File file = new File(outDir_Field.getText() + File.separator + SingleGetPic.pname.replace(" ", "_"));
                File[] files = file.listFiles();
                if (files != null)
                    albumIndexField.setText(String.valueOf(files.length));
            }else{
                JOptionPane.showMessageDialog(jFrame, "请先填写图片保存位置!");
            }

        });


        JPanel line_1 = new JPanel(); // new FlowLayout(FlowLayout.LEFT)
        JLabel from_label = new JLabel("开始索引:", JLabel.LEFT);
        from_label.setForeground(Color.RED);
        from_label.setOpaque(false);
        from_label.setFont(new Font("楷体", Font.BOLD, 20));
        fromField = new JTextField();
        fromField.setOpaque(false);
        fromField.setColumns(10);
        fromField.setFont(new Font("楷体", Font.BOLD, 20));

        JLabel to_label = new JLabel("结束索引:");
        to_label.setForeground(Color.RED);
        to_label.setFont(new Font("楷体", Font.BOLD, 20));
        toField = new JTextField();
        toField.setOpaque(false);
        toField.setColumns(10);
        toField.setFont(new Font("楷体", Font.BOLD, 20));


        line_1.add(from_label);
        line_1.add(fromField);
        line_1.add(to_label);
        line_1.add(toField);


        JPanel line_1_1 = new JPanel();
        line_1_1.setOpaque(false);
        JLabel album_label = new JLabel("当前专辑序号:");
        album_label.setForeground(Color.RED);
        album_label.setFont(new Font("楷体", Font.BOLD, 20));
        albumIndexField = new JTextField("0");
//        albumIndexField.setEnabled(false);
        albumIndexField.setOpaque(false);
        albumIndexField.setColumns(5);
        albumIndexField.setFont(new Font("楷体", Font.BOLD, 20));

        JLabel album_label_total = new JLabel("当前MM共有专辑数:");
        album_label_total.setForeground(Color.RED);
        album_label_total.setFont(new Font("楷体", Font.BOLD, 20));
        albumTotalField = new JTextField("0");
        albumTotalField.setOpaque(false);
        albumTotalField.setColumns(5);
        albumTotalField.setFont(new Font("楷体", Font.BOLD, 20));
        albumTotalField.setEnabled(false);

        line_1_1.add(album_label_total);
        line_1_1.add(albumTotalField);
        line_1_1.add(album_label);
        line_1_1.add(albumIndexField);

        JPanel line_2 = new JPanel();
        pname_label = new JLabel("-------MM名称-------");
        pname_label.setForeground(Color.RED);
        pname_label.setFont(new Font("楷体", Font.BOLD, 20));
        line_2.add(pname_label);

        JPanel line_3 = new JPanel();
        album = new JLabel("--------专辑名称---------");
        album.setForeground(Color.RED);
        album.setFont(new Font("楷体", Font.BOLD, 15));
        index = new JLabel("XXX");
        index.setForeground(Color.YELLOW);
        index.setFont(new Font("楷体", Font.BOLD, 15));
        line_3.add(album);
        line_3.add(index);

        JPanel line_4 = new JPanel();
        JLabel outDir_label = new JLabel("图片保存位置:");
        outDir_label.setForeground(Color.RED);
        outDir_label.setFont(new Font("楷体", Font.BOLD, 20));
        outDir_Field = new JTextField();
        outDir_Field.setForeground(Color.RED);
        outDir_Field.setColumns(30);
        outDir_Field.setOpaque(false);
        outDir_Field.setFont(new Font("楷体", Font.BOLD, 15));
        line_4.add(outDir_label);
        line_4.add(outDir_Field);

        line_0.setOpaque(false);
        line_1.setOpaque(false);
        line_2.setOpaque(false);
        line_3.setOpaque(false);
        line_4.setOpaque(false);

        // 开始按钮
        JPanel line_5 = new JPanel(); // new FlowLayout(FlowLayout.LEFT)
        line_5.setOpaque(false);
        ImageIcon button_ico = new ImageIcon(Objects.requireNonNull(PicView.class.getResource("/bg.jpg")));
        button_ico.setImage(button_ico.getImage().getScaledInstance(40, 20, Image.SCALE_DEFAULT));
        start_button = new JButton("开  始", button_ico);
        start_button.setOpaque(false);
        start_button.setFont(new Font("楷体", Font.BOLD, 20));
        start_button.setForeground(new Color(92, 245, 10));
        line_5.add(start_button);

        jPanel.add(line_4);
        jPanel.add(line_0);
        jPanel.add(line_1);
        jPanel.add(line_1_1);
        jPanel.add(line_2);
        jPanel.add(line_3);

        jPanel.add(line_5);


        // 创建对象
        SingleGetPic singleGetPic = new SingleGetPic();
        // 给开始按钮添加监听事件
        start_button.addActionListener(e -> {
            // 将循环抽取数据写到一个单独的线程中
//                new Thread(){}.start();
            // run
            new Thread(() -> {
                String text = start_button.getText();
                if ("开  始".equals(text)) {
                    start_button.setText("停  止");
                    start_button.setForeground(new Color(223, 13, 13));
                    // 从视图中获取数据
                    String start_str = fromField.getText();
                    String end_str = toField.getText();
                    String albumIndex_str = albumIndexField.getText();
                    String outDirFieldText = outDir_Field.getText();

                    // 判断是否全部输入
                    if (StringUtils.isEmpty(start_str) || StringUtils.isEmpty(end_str) || StringUtils.isEmpty(albumIndex_str) || StringUtils.isEmpty(outDirFieldText)) {
                        JOptionPane.showMessageDialog(jFrame, "数据还没填写完呢,不要那么心急!!!");
                        stopPD();
                        return;
                    }
                    // 对数据转换赋值
                    int start = Integer.parseInt(start_str);
                    fromField.setEnabled(false);
                    int end = Integer.parseInt(end_str);
                    toField.setEnabled(false);
                    SingleGetPic.current_album = Integer.parseInt(albumIndex_str) - 1;
                    albumIndexField.setEnabled(false);
                    SingleGetPic.outDir = outDirFieldText;
                    outDir_Field.setEnabled(false);

                    // 启动下载
                    SingleGetPic.isDownLoad = true;
                    SingleGetPic.isErr = false;
                    boolean getPicPic = singleGetPic.getPic(start, end);
                    if (!getPicPic) {
                        JOptionPane.showMessageDialog(jFrame, "下载完成,点击确定后关闭应用!");
                        System.exit(0);
                    } else {
                        JOptionPane.showMessageDialog(jFrame, "异常停止,程序不会关闭!");
//                                System.exit(0);
                    }


                } else {
                    stopPD();
                }
            }).start();

        });
    }

    /**
     * 功能描述
     *
     * @param string 传入的字符串
     * @return true:传入的字符串为空 , false:传入的字符串不为空
     */
    private static boolean isEmpty(String string) {
        if (string == null || string.length() == 0 || string.replace(" ", "").length() == 0) {
            return true;
        }
        return false;
    }

    static void checkPeerPersonAlbum(String fromIndex) {
        {
            Element element = SingleGetPic.getElements().get(Integer.parseInt(fromIndex));
            SingleGetPic.pname = element.text();
            PicView.pname_label.setText(SingleGetPic.pname);
            String href = element.attr("href");
            String peer = SingleGetPic.prefix + href;
            SpiderHttpClient peer_response = new SpiderHttpClient(peer, "GET", "UTF-8", null);
            String peer_responseResponseStr = peer_response.getResponseStr();
            Document peer_responseResponseStr_document = Jsoup.parse(peer_responseResponseStr);
            Elements peer_responseResponseStr_elements = peer_responseResponseStr_document.select("body > div.box > div > div.index_middle_c > ul > li > a");
            SingleGetPic.albumAmount = peer_responseResponseStr_elements.size();
            Elements list_page = peer_responseResponseStr_document.select("body > div.box > div > div.list_page");
            int childNodeSize = list_page.get(0).childNodeSize();
            for (int i = 1; i < childNodeSize; i++) {
                Node childNode = list_page.get(0).childNode(1);
                String next_list = childNode.attr("href");
                String next = SingleGetPic.prefix + next_list;
                SpiderHttpClient next_response = new SpiderHttpClient(next, "GET", "UTF-8", null);
                String next_responseResponseStr = next_response.getResponseStr();
                Document next_responseResponseStr_document = Jsoup.parse(next_responseResponseStr);
                Elements next_responseResponseStr_elements = next_responseResponseStr_document.select("body > div.box > div > div.index_middle_c > ul > li > a");
                SingleGetPic.albumAmount += next_responseResponseStr_elements.size();
            }
            PicView.albumTotalField.setText(SingleGetPic.albumAmount + "");
        }
    }
}
